package com.jason.kotlin.utils

/**
 * Description:IDCardUtil
 *
 * @author 陈宝阳
 * @create 2020/11/7 14:22
 */
object IDCardUtil {
    /**
     * wi =2(n-1)(mod 11)  权重因子
     */
    private val wi = intArrayOf(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1)

    /**
     * 验证的数字
     */
    private val vi = intArrayOf(1, 0, 'X'.toInt(), 9, 8, 7, 6, 5, 4, 3, 2)

    /**
     * 身份证校验合法性
     *
     * @param idCard
     * @return
     */
    fun Verify(idCard: String): Boolean {
        var idCard = idCard
        if (idCard.length == 15) {
            idCard = upToEighteen(idCard)
        }
        if (idCard.length != 18) {
            return false
        }
        val verify = idCard.substring(17, 18)
        return verify == getVerify(idCard)
    }

    /**
     * 身份证格式规则校验，第十八位的数字，来自前17位的换算
     *
     * @param cardId
     * @return
     */
    private fun getVerify(cardId: String): String {
        var cardId = cardId
        var remaining = 0
        val ai = IntArray(18)
        if (cardId.length == 18) {
            cardId = cardId.substring(0, 17)
        }
        if (cardId.length == 17) {
            var sum = 0
            for (i in 0..16) {
                val k = cardId.substring(i, i + 1)
                ai[i] = k.toInt()
            }
            for (i in 0..16) {
                sum += wi[i] * ai[i]
            }
            remaining = sum % 11
        }
        return if (remaining == 2) "X" else vi[remaining].toString()
    }

    /**
     * 将早期旧的15位身份证升级到18位，进行校验
     *
     * @param cardId
     * @return
     */
    private fun upToEighteen(cardId: String): String {
        var newCardId = cardId.substring(0, 6)
        newCardId += "19"
        newCardId += cardId.substring(6, 15)
        newCardId += getVerify(newCardId)
        return newCardId
    }
}